﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using ComicQ.Controller;
using ComicQ.Domain.Table;

namespace ComicQ.Dektop.View
{
    /// <summary>
    /// Interaction logic for StaffView.xaml
    /// </summary>
    public partial class StaffView
    {
        private readonly StaffController _staffControl;
        private IList<Staff> _staves;

        public StaffView()
        {
            InitializeComponent();

            _staffControl = new StaffController();
            _staves = _staffControl.GetAllStaff();
            dataGridStaff.ItemsSource = _staves;
        }

        private void RefreshGrid()
        {
            dataGridStaff.ItemsSource = null;
            _staves = _staffControl.GetAllStaff();
            dataGridStaff.ItemsSource = _staves;
        }

        private void ButtonAddClick(object sender, RoutedEventArgs e)
        {
            var newWindow = new StaffEditorView();

            if (newWindow.ShowDialog() != false)
            {
            }
            else
            {
                RefreshGrid();
            }
        }

        private void ButtonDeleteClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dataGridStaff.SelectedItem == null)
                    throw new NullReferenceException();

                var staff = _staves
                        .Where(m => m.Id == _staves[dataGridStaff.SelectedIndex].Id)
                        .Select(m => m)
                        .Single();

                _staffControl.DeleteStaff(staff);
                MessageBox.Show("sukses menghapus staff");
                RefreshGrid();
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("pilih yang mau didelete.");
            }
        }

        private void ButtonEditClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dataGridStaff.SelectedItem == null)
                    throw new NullReferenceException();

                var newWindow = new StaffEditorView(_staves[dataGridStaff.SelectedIndex]);

                if (newWindow.ShowDialog() != false)
                {
                }
                else
                {
                    RefreshGrid();
                }
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("pilih yang mau diedit");
            }
        }
    }
}
